//
//  AppointmentViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/4/12.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import CRRefresh
import Alamofire
class AppointmentViewController: BaseViewController {
    @IBOutlet var appointmentTableview: UITableView!
    let appointmentCell = "appointmentCell"
    let appointmentDidOrRefuseCell = "appointmentDidOrRefuseCell"
    var appointments:[AppointmentModel]?
    var status:Int? //0 未接单 1 已接单  2 已完成 3 已拒绝
    var sendStatus:Int?
    override func viewDidLoad() {
        super.viewDidLoad()
        initSegmentControl()
        configView()
        page = 1
        status = 0
        sendStatus = 0
        requstAppointmentList(page: page!, status: sendStatus!)
        
    }

    func initSegmentControl() -> Void {
        let btnDataSource = ["未接单","已接单","已完成","已拒绝"]
        let yysegment = YJSegmentedControl.init(frame: CGRect(x:0,y:0,width:kScreenWidth,height:44), titleDataSource: btnDataSource, backgroundColor: UIColor.white, titleColor: BaseColor.DarkGrayColor, titleFont: UIFont.systemFont(ofSize: 14), select: BaseColor.NavColor, buttonDownColor: BaseColor.NavColor, delegate: self)
        self.view .addSubview(yysegment!)
    }
    
    func configView() -> Void {
        appointmentTableview.delegate = self
        appointmentTableview.dataSource = self
        appointmentTableview.separatorStyle = .none
    appointmentTableview.showsVerticalScrollIndicator = false
        appointmentTableview.backgroundColor = BaseColor.BackGroundColor
        appointmentTableview.register(UINib(nibName: "AppointmentTableViewCell", bundle: nil), forCellReuseIdentifier: appointmentCell)
        appointmentTableview.register(UINib(nibName: "AppointmentDidOrRefuseTableViewCell", bundle: nil), forCellReuseIdentifier: appointmentDidOrRefuseCell)
        appointmentTableview.cr.addHeadRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol) { [weak self] in
            page = 1
            self?.requstAppointmentList(page: page!, status: (self?.sendStatus!)!)
        }
        appointmentTableview.cr.addFootRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol)  { [weak self] in
            page! += 1
            self?.requstAppointmentList(page: page!, status: (self?.sendStatus!)!)
        }
    }
    
    //网络请求
    //请求预约订单列表
    func requstAppointmentList(page:Int,status:Int) -> Void {
        
        Alamofire.request(appointmentListUrl, method:.post, parameters: ["page": page,"status":status,"storeid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in
                self.appointmentTableview?.cr.endHeaderRefresh();                self.appointmentTableview?.cr.endLoadingMore()
                switch response.result.isSuccess {
                case true:
                    var basemodel = BaseResponseOfModel<BaseArrayData<AppointmentModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                    
                        if page == 1 {
                            self.appointments?.removeAll()
                            self.appointments = basemodel.data?.data
                        }else {
                            if ((basemodel.data?.data?.count)! > 0) {
                                self.appointments! += (basemodel.data?.data)!
                            }else {
                                return
                            }
                        }
                        self.appointmentTableview.reloadData()
                        
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                case false:
                    print(response.result.error!)
                }
        }
    }
    
    //拒绝预约订单
    func requestRefuseAppoint(appointId:String) -> Void {
        
        
        Alamofire.request(refuseAppointUrl, method:.post, parameters:["id":appointId])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        page = 1
                        self.requstAppointmentList(page: page!, status: self.sendStatus!)
                        print("成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //接受预约订单
    func requestAcceptAppoint(appointId:String) -> Void {
        
        
        Alamofire.request(acceptAppointUrl, method:.post, parameters:["id":appointId])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        page = 1
                        self.requstAppointmentList(page: page!, status: self.sendStatus!)
                        print("成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //生成订单
    func requestProduceOrder(appointId:String,type:String,price:String,remarks:String,code:String) -> Void {
//        type 0 未支付  1 已支付 2 未支付的需求发布
        var param :Dictionary<String, Any>?
        switch type {
        case "0":
             param =
                ["id":appointId,
                 "type":type,
                 "price":price,
                 "description":remarks,
                 "code":code
            ]
        case "1":
            param =
                ["id":appointId,
                 "type":type,
                 "code":code
            ]
        default:
            param =
                ["id":appointId,
                 "type":"0",
                 "price":price,
                 "description":remarks,
            ]
        }
        
        Alamofire.request(createOrderUrl, method:.post, parameters:param)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        //                        self.page = 1
                        //                        self.requstEmpolyList(page: self.page!, pageSize: pageSize)
                        MBProgressHUD.alertShow(in: self.view, message:"生成订单成功", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                        page = 1
                        self.requstAppointmentList(page: page!, status: self.sendStatus!)
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension AppointmentViewController: YJSegmentedControlDelegate,UITableViewDelegate,UITableViewDataSource {
    
    func segumentSelectionChange(_ selection: Int) {
        page = 1
        status = selection
        switch status {
        case 0:
            sendStatus = 0
        case 1:
            sendStatus = 1
        case 2:
            sendStatus = 3
        default:
            sendStatus = 2
        }
        requstAppointmentList(page: page!, status: sendStatus!)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.appointments?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if (status! == 0||status! == 1)  {
            let cell = tableView.dequeueReusableCell(withIdentifier: appointmentCell, for: indexPath) as! AppointmentTableViewCell
            cell.selectionStyle = .none
            let model = self.appointments![indexPath.item]
            if (status! == 0){//未接单 两个按钮
                cell.getOrderBtn.isHidden = false
                cell.refuseOrderBtn.isHidden = false
                cell.flishOrderBtn.isHidden = true
            }else {//已接单 一个按钮
                cell.getOrderBtn.isHidden = true
                cell.refuseOrderBtn.isHidden = true
                cell.flishOrderBtn.isHidden = false
            }
            if model.member_car != nil {
                cell.carInfoLabel.text = "车牌号：" + (model.member_car?.prov_key)! + (model.member_car?.num)!
            }
            if model.member != nil {
                cell.userImageView.sd_setImage(with: (NSURL(string:(model.member?.avatar)!)! as URL), placeholderImage: UIImage.init(named: "defultHeaderImg"))
            }
            if ((model.server) != nil){
                cell.serviceTypeLabel.text = "服务类型：" + (model.server?.name)!
            }
            cell.userNameLabel.text = "姓名：" + model.name
            cell.userPhoneLabel.text = "电话：" + model.phone
            cell.appointmentNumLabel.text = "预约单号：" + model.bespeakordersn
            cell.remarksLabel.text = "备注：" + model.content
            
            cell.downOrderLabel.text = "下单时间：" + model.addtime
            cell.arriveTimeLabel.text = "到店时间：" + model.bespeaktime
            cell.userImageView.roundCorner(radius: cell.userImageView.frame.height/2)
            
            cell.callBackBlock { (btnIndex) in
            switch btnIndex {
                
                case 1://拒绝
                    let alertController = UIAlertController(title: "温馨提示",
                                                            message: "是否拒绝预约订单？", preferredStyle: .alert)
                    let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                    let okAction = UIAlertAction(title: "确定", style: .default, handler: {
                        action in
//                        print("拒绝")
                        self.requestRefuseAppoint(appointId: model.id)
                    })
                    alertController.addAction(cancelAction)
                    alertController.addAction(okAction)
                    self.present(alertController, animated: true, completion: nil)
                case 2://接受
                    let alertController = UIAlertController(title: "温馨提示",
                                                            message: "是否接受预约订单？", preferredStyle: .alert)
                    let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                    let okAction = UIAlertAction(title: "确定", style: .default, handler: {
                        action in
                        print("接受")
                        self.requestAcceptAppoint(appointId: model.id)
                    })
                    alertController.addAction(cancelAction)
                    alertController.addAction(okAction)
                    self.present(alertController, animated: true, completion: nil)
                default://完成
                    print("完成订单")
                    
                    let produceOrderView = ProduceOrderView.getProduceOrderPopView()
                    var orderType = ""
                    
                    if model.orderid == "0" {
                       
                        if (model.task_id != ""){//需求预约
                          produceOrderView.codeTF.isHidden = true
                            orderType = "2"
                        }else {//其他预约 未给钱
                            
                            produceOrderView.priceTF.isHidden = false
                            produceOrderView.remarksTF.isHidden = false
                            
                            orderType = "0"

                        }
                    }else {//洗车预约 提前给钱
                        produceOrderView.priceTF.isHidden = true
                        produceOrderView.remarksTF.isHidden = true
                        orderType = "1"
                    }
                    produceOrderView.callBackBlock { (boolValue) in
                        switch boolValue {
                        case true:
                   if orderType == "0"{//未支付
                    
                   
                        if (produceOrderView.remarksTF.text == "")||(produceOrderView.codeTF.text == "")||(produceOrderView.priceTF.text == ""){
                            MBProgressHUD.alertShow(in: produceOrderView, message: "请填写完整再提交", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                            return
                    }
                    
                   }else if orderType == "1" {//已支付
                    if (produceOrderView.codeTF.text == ""){
                         MBProgressHUD.alertShow(in: produceOrderView, message: "请填写验证码后再提交", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                        return
                    }
                   }else {//需求发布类型
                    if (produceOrderView.remarksTF.text == "")||(produceOrderView.priceTF.text == ""){
                        MBProgressHUD.alertShow(in: produceOrderView, message: "请填写完整再提交", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                        return
                    }
                   }
                    self.requestProduceOrder(appointId: model.id, type:orderType, price: produceOrderView.priceTF.text!, remarks: produceOrderView.remarksTF.text!, code: produceOrderView.codeTF.text!)
                            bgWindow?.hidBackgroundWindow()
                        case false:
                            bgWindow?.hidBackgroundWindow()
                        }
                    }
                    bgWindow = DSHCBcakgroundWindow.setupBackgroundWindowAndShow()
                    bgWindow?.shake(toShow: produceOrderView)
                }
                
            }
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: appointmentDidOrRefuseCell, for: indexPath) as! AppointmentDidOrRefuseTableViewCell
            cell.selectionStyle = .none
            let model = self.appointments![indexPath.item]
            cell.userNameLabel.text = "姓名：" + model.name
            if model.member_car != nil {
                cell.carInfoLabel.text = "车牌号：" + (model.member_car?.prov_key)! + (model.member_car?.num)!
            }
            if model.member != nil {
                cell.userImageView.sd_setImage(with: (NSURL(string:(model.member?.avatar)!)! as URL), placeholderImage: UIImage.init(named: "defultHeaderImg"))
            }
            if ((model.server) != nil){
                cell.serviceTypeLabel.text = "服务类型：" + (model.server?.name)!
            }
            cell.userPhoneLabel.text = "电话：" + model.phone
            cell.appointmentNumLabel.text = "预约单号：" + model.bespeakordersn
            cell.remarksLabel.text = "备注：" + model.content
            cell.downOrderLabel.text = "下单时间：" + model.addtime
            cell.arriveTimeLabel.text = "到店时间：" + model.bespeaktime
            
            cell.userImageView.roundCorner(radius: cell.userImageView.frame.height/2)
            
            if (status! == 2){
                cell.payStatusLabel.isHidden = false;
                //已完成 区分已付款和待付款
                if (model.payment == "0"){
                    //待付款
                    cell.payStatusLabel.textColor = UIColor.red
                    cell.payStatusLabel.text = "未付款"
                }else {
                    //已付款
                    
                    cell.payStatusLabel.textColor = BaseColor.NavColor
                    cell.payStatusLabel.text = "已付款"
                }
                
            }else {
                cell.payStatusLabel.isHidden = true;
            }
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (status! == 0||status! == 1)  {
            return ScaleHeight(215)
        }else {
            return ScaleHeight(180)
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
//    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        return 10
//    }
    
}

